
<style scoped>
.ai-summary-popup {
  width: 100%;
  height: 100%;
  padding: 20px;
  margin: 0;
  background-color: #f5f5f5;
}

.popup-card {
  width: 100%;
  height: 100%;
  border: none;
  box-shadow: none;
}

.card-header {
  text-align: center;
  padding: 0;
}

.card-header h3 {
  margin: 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
}

.url-section {
  margin-bottom: 20px;
}

.input-label {
  display: block;
  margin-bottom: 8px;
  color: #606266;
  font-size: 14px;
  font-weight: 500;
}

.input-field {
  width: 100%;
}

.button-section {
  text-align: center;
  margin-bottom: 20px;
}

.summary-button {
  padding: 12px 24px;
  font-size: 14px;
  border-radius: 6px;
}

.result-section {
  margin-top: 20px;
}

.result-section h4 {
  margin: 0 0 12px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.result-card {
  margin-top: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
}

.empty-result {
  text-align: center;
  color: #909399;
  font-size: 14px;
  padding: 40px 20px;
  background-color: #fafafa;
  border: 1px dashed #d3d4d6;
  border-radius: 6px;
}

.cache-tip {
  margin-top: 12px;
  text-align: center;
}

.cache-tip .el-tag {
  font-size: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .card-header h3 {
    font-size: 16px;
  }

  .summary-button {
    padding: 10px 20px;
    font-size: 13px;
  }

  .input-label {
    font-size: 13px;
  }
}
</style>

<template>
  <div class="ai-summary-popup">
    <div slot="header" class="card-header">
      <h3>AI总结文章</h3>
    </div>

    <section>
      <!-- URL输入框 -->
      <div class="url-section">
        <label class="input-label">文章URL地址：</label>
        <el-input
            v-model="articleUrl"
            class="input-field"
            placeholder="请输入文章URL地址..."
            type="textarea"
            :rows="2"
        />
      </div>

      <!-- 总结按钮 -->
      <div class="button-section">
        <el-button
            class="summary-button"
            type="primary"
            @click="handleSummaryArticle"
            icon="el-icon-document"
            v-loading="loading"
            :disabled="!articleUrl.trim()"
            size="medium"
        >
          总结文章
        </el-button>
        <el-button
            class="summary-button"
            type="primary"
            icon="el-icon-document"
            v-loading="loadoing3"
            :disabled="!articleUrl.trim()"
            size="medium"
            @click="handleAddToNotes"
        >
          保存为笔记
        </el-button>
      </div>
    </section>


    <!-- 笔记库存的相关笔记 -->
    <div class="result-section"  v-if="relatedConceptsInNote.length > 0">
      <h4>笔记库存的相关笔记</h4>
      <el-card v-if="relatedConceptsInNote.length > 0" class="result-card">
        <ul class="related-concepts-list">
          <li v-for="(item, index) in relatedConceptsInNote" :key="index">

            <div>
              <el-popover :title="item?.name"  trigger="click">
                <div style="max-width: 555px;overflow: auto;max-height: 450px;">
                  <MdShow :value="item?.content" />
                </div>
                <div slot="reference" style="color: #66b1ff;cursor:pointer;">
                  {{ index + 1 }}. {{ item?.name }}
                </div>
              </el-popover>



            </div>
          </li>
        </ul>
      </el-card>
      <div v-else class="empty-result">
        文档库暂时没有这方面的数据
      </div>
    </div>


    <!-- 总结结果区域 -->
    <div class="result-section" v-loading="loading">
      <h4>文章总结结果</h4>
      <el-card v-if="summaryResult" class="result-card">
        <MdShow :value="summaryResult" />
      </el-card>
      <div v-else class="empty-result">
        等待总结结果...
      </div>
    </div>

    <!-- 缓存提示 -->
    <div v-if="fromCache" class="cache-tip">
      <el-tag type="info" size="mini">
        <i class="el-icon-time"></i>
        此结果来自缓存
      </el-tag>
    </div>
  </div>
</template>

<script>
import MdShow from '../../components/MdShow.vue';

export default {
  name: 'PopupSummary',
  components: {
    MdShow
  },
  data() {
    return {
      loadoing3: false,
      articleUrl: '',
      loading: false,
      summaryResult: '',
      fromCache: false,
      relatedConceptsInNote:[]
    };
  },
  mounted() {
    // 获取当前页面的URL
    this.getCurrentPageUrl();
  },
  methods: {
    /**
     * 获取当前页面URL
     */
    async getCurrentPageUrl() {
      try {
        // 从storage获取选中的文本并填充到输入框
        chrome.storage.local.get('currentUrl', (result) => {
          console.log("result : -->  ","color:#f0f;", result);

          if (result.currentUrl) {
            this.articleUrl = result.currentUrl;
          }
        });
      } catch (error) {
        console.error('获取当前页面URL失败:', error);
        // 如果无法获取，则显示提示
        this.articleUrl = '请手动输入文章URL地址';
      }
    },

    /**
     * 处理总结文章按钮点击事件
     */
    async handleSummaryArticle() {
      if (!this.articleUrl?.trim()) {
        this.$message.warning('请输入文章URL地址');
        return;
      }

      try {
        this.loading = true;
        this.summaryResult = '';
        this.fromCache = false;

        // 调用后端API进行文章总结
        const result = await this.callsummaryApi(this.articleUrl.trim());
        
        if (result.success) {
          this.summaryResult = result.data?.summary || '未获取到总结内容';
          this.fromCache = result.data?.fromCache || false;
          
          if (this.fromCache) {
            this.$message.success('总结完成（来自缓存）');
          } else {
            this.$message.success('总结完成');
          }
        } else {
          this.$message.error(result.message || '总结失败');
        }
      } catch (error) {
        this.$message.error('总结失败，请重试');
        console.error('文章总结错误:', error);
      } finally {
        this.loading = false;
      }
    },

    /**
     * 调用后端总结接口
     * @param {string} url - 文章url
     */
    async callsummaryApi(url) {
      const response = await fetch('http://localhost:9001/api/ai/summary', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ url })
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      return response.json();
    },
    /**
     * 搜索相关笔记
     */
    async searchRelatedNotes() {
      if (!this.articleUrl.trim()) {
        this.relatedConceptsInNote = [];
        return;
      }

      try {
        this.loadoing6 = true;

        // 调用后端API搜索相关笔记
        const response = await fetch(`http://localhost:9001/api/knowledge/searchRelated?query=${encodeURIComponent(this.articleUrl.trim())}`, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json'
          }
        });

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        const result = await response.json();

        if (result.success) {
          this.relatedConceptsInNote = result.data || [];
        } else {
          console.error('搜索相关笔记失败:', result.message);
          this.relatedConceptsInNote = [];
        }
      } catch (error) {
        console.error('搜索相关笔记错误:', error);
        this.relatedConceptsInNote = [];
      } finally {
        this.loadoing6 = false;
      }
    },

    /**
     * 处理加入笔记按钮点击事件
     */
    async handleAddToNotes() {
      if (!this.summaryResult || !this.articleUrl.trim()) {
        this.$message.warning('请先进行AI查询获取结果');
        return;
      }

      try {
        this.loadoing3 = true;

        // 构建笔记内容
        const content = `${this.articleUrl}\n\n---\n\n文章总结：\n${this.summaryResult}`;

        // 调用后端API创建知识库
        const response = await fetch('http://localhost:9001/api/knowledge/create', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            name: this.articleUrl.trim(),
            content: content
          })
        });

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        const result = await response.json();

        if (result.success) {
          this.$message.success('笔记添加成功！');
          // 重新搜索相关笔记
          await this.searchRelatedNotes();
        } else {
          this.$message.error(result.message || '添加笔记失败');
        }
      } catch (error) {
        this.$message.error('添加笔记失败，请重试');
        console.error('添加笔记错误:', error);
      } finally {
        this.loadoing3 = false;
      }
    }
  }
};
</script>
